package com.lnsoft.dqfs.server.util;

import com.lnsoft.dqfs.server.handle.codec.Frame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 升级包缓存
 * 定时更新看是否有最新的
 */
@Component
@Slf4j
public class UpgradePackageCache {

    private static final int packageSize = 200;

    @Value("${upgrade.package.dir}")
    private String fileDir;

    // TODO 子站有没有升级需求

    private volatile UpgradePackage upgradePackage;


    public String getFileName(){
        return upgradePackage.getVersion();
    }


    public int offset(Frame frame){
        return frame.getUpgradePackageindex() * packageSize;
    }

    public int getPackageSize(){
        return upgradePackage.getLength();
    }

    /**
     * 是否是最后一个
     * @param index
     * @return
     */
    public boolean isReadEnd(int index){
        if(index == upgradePackage.getPackages().size()-1){
            return true;
        }
        return false;
    }

    public byte[] getUpgradePackageByIndex(int index){
        return upgradePackage.getPackages().get(index);
    }

    /**
     * 是否符合升级条件
     * @param version
     * @return
     */
    public boolean isUpgradePackage(String version){
//        if(upgradePackage==null || upgradePackage.getVersion().equals(version)){
        if(upgradePackage==null){
            return false;
        }
        return true;
    }


    @Scheduled(cron = "0 45 23 * * ?")     // 每天的23:45 查看指定目录下是否有升级文件
    public void updateUpgradePackage() {
        UpgradePackage newUpgradePackage = null;
        RandomAccessFile raf = null;

        log.debug("定时器开始启动");
        try {
            File dir = new File(fileDir);
            if (!dir.exists()) {
                return;
            }
            File[] files = dir.listFiles();
            if (files.length != 1) {
                return;
            }
            File file = files[0];
            String fileName = file.getName();
            List<byte[]> packages = new LinkedList<>();

            raf = new RandomAccessFile(file, "r");
            int length = (int)raf.length(); // 报文中长度4个字节 强转为int

            int index = 0;
            while(true){
                if(length-index<=0){
                    break;
                }
                byte[] buf ;
                if(length-index<packageSize){
                    buf = new byte[(length-index)];
                }else{
                    buf = new byte[packageSize];
                }
                raf.read(buf);
                log.debug("index:{},buf:{}",index,Arrays16.toString(buf));
                packages.add(buf);
                index = index+packageSize;
            }

            newUpgradePackage = UpgradePackage.builder()
                    .length(length)
                    .version(fileName)      //  升级文件名要写成版本号如:SV06.014.bin
                    .packages(new ArrayList<>(packages)).build();
            log.debug("文件大小:{},文件名:{}packags-size:{}",length,fileName,
                    newUpgradePackage.getPackages().size());

//            log.info("升级文件名(版本号)：{}",getFileName());
//            log.info("升级文件大小：{}字节",getPackageSize());


        } catch (Exception e) {
            log.error("定时执行error!!!", e);
        } finally {
            log.debug("定时器执行完毕");
            upgradePackage = newUpgradePackage;
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


}
